
source("util_pivotality_functions.R")
ss = c(10, 25, 40, 53, 55, 70, 85)

# for predictions 
p = read.csv("FED_backend_data with winningCandidate.csv")
# results 
res = read.csv("table_tableau12_2015.csv")
pp = p[,grepl("^projection", colnames(p))]
# now cycle through ss to do this 

for(s in ss){
  
  cat("****** s = ", s, " *********\n", sep = "")
  #### Predictions based ####  
  pp = p[,grepl("^projection", colnames(p))]
  
  for(j in 1:ncol(pp)){
    pp[,j] = as.numeric(gsub("%", "", pp[,j]))/100
  }
  
  colnames(pp) = c("con", "lib", "ndp", "bq", "grn", "oth")
  # so now we want to do the pp.vec thing. 
  
  pp.mat = matrix(NA, nrow = 0, ncol = 15)
  for(i in 1:nrow(pp)){
    if(i%%10 == 0){cat(i, " ")}
    pp.vec = pivotal.probabilities.analytical(unlist(pp[i,]*s))	
    pp.mat = rbind(pp.mat, pp.vec)
  }
  cat("Done.\n")
  
  pp.mat = cbind(p$constituencyNumber, 1000000*pp.mat)
  
  colnames(pp.mat)[1] = "constituency_number"
  
  write.csv(pp.mat, row.names = F, file = paste0("pivot_probs_x1M_2015_canada_s_", s, ".csv" ))
  
  
  ### results based ### 
  
  res$party = "oth"
  patterns = c("Liberal", "Conservative", "NDP", "Bloc Q", "Green Par")
  parties = c("lib", "con", "ndp", "bq", "grn")
  for(i in 1:length(patterns)){
    res$party[grepl(patterns[i], res$Candidate.Candidat)] = parties[i]
  }
  
  eds = unique(res$Electoral.District.Number.Numéro.de.circonscription)
  parties.plus = c(parties, "oth")
  party.votes = matrix(0, nrow = length(eds), ncol = length(parties.plus))
  colnames(party.votes) = parties.plus
  for(i in 1:length(eds)){
    for(j in 1:length(parties.plus)){
      indices = which(res$Electoral.District.Number.Numéro.de.circonscription == eds[i] & res$party == parties.plus[j])
      if(length(indices) == 0){next}
      party.votes[i,j] = sum(res$Votes.Obtained.Votes.obtenus[indices])
    }
  }
  
  party.vote.shares = party.votes/apply(party.votes, 1, sum)
  res2 = as.data.frame(cbind(eds, party.vote.shares))
  
  pp.mat = matrix(NA, nrow = 0, ncol = 15)
  for(i in 1:nrow(res2)){
    if(i%%10 == 0){cat(i, " ")}
    pp.vec = pivotal.probabilities.analytical(unlist(res2[i,-1]*s))	
    pp.mat = rbind(pp.mat, pp.vec)
  }
  cat("Done.\n")
  
  pp.mat = cbind(res2[,1], 1000000*pp.mat)
  
  colnames(pp.mat)[1] = "constituency_number"
  
  write.csv(pp.mat, row.names = F, file = paste0("pivot_probs_x1M_2015_canada_s_", s, "_results.csv" ))
  
}

# I use this to exclude ridings where others got significant vote shares

colnames(res2)[1] = "constituency_number"
write.csv(res2, row.names = F, file = "vote_shares_by_riding_2015.csv")

